#!/usr/bin/env python
#import pyLikelihood as pyLike
import BinnedAnalysis as BAn

def getTS(srcMaps, expCube, binnedExpMap, srcModel, irfs):
    obs = BAn.BinnedObs(srcMaps=srcMaps, expCube=expCube,
                        binnedExpMap=binnedExpMap, irfs=irfs)
    like = BAn.BinnedAnalysis(obs, srcModel, optimizer='MINUIT')
#   likeobj = pyLike.Minuit(like.logLike)

    counts = 0
    for src in like.sourceNames():
        if like[src].src.fixedSpectrum():
            counts += like.NpredValue(src)
            continue

        npred = like.NpredValue(src)
        ts = like.Ts(src)
        counts += npred
        print('[%s] TS=%.3f, npred=%.2f' % (src, ts, npred))

    print ("Model Cnts / Obs Cnts: %s / %s = 1.%+.5f" %
           (counts, like.total_nobs(), counts/like.total_nobs()-1.))


def cli():
    import argparse

    parser = argparse.ArgumentParser(description='Get TS Value')
    parser.add_argument("srcMaps", type=str, help='Source Maps')
    parser.add_argument("expCube", type=str, help='Live Time Cube')
    parser.add_argument("binnedExpMap", type=str, help='Exposure Cube')
    parser.add_argument("srcModel", type=str, help='model.xml')
    parser.add_argument("irfs", type=str, help='IRFs')

    args = parser.parse_args()

    getTS(args.srcMaps, args.expCube, args.binnedExpMap, args.srcModel, args.irfs)

if __name__ == '__main__': cli()
